package com.shujia.flink.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Properties;

public class Demo03WordCountOnKafka {
    public static void main(String[] args) throws Exception {
        // 读Kafka，统计单词的数量，将结果写入Kafka
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 在集群中的配置文件中统一开启CheckPoint

        KafkaSource<String> kafkaSource = KafkaSource
                .<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                // 创建Topic：kafka-topics.sh --zookeeper master:2181/kafka --topic words_01 --partitions 1 --replication-factor 1 --create
                // 生产数据：kafka-console-producer.sh --broker-list master:9092,node1:9092,node2:9092 --topic words_01
                .setTopics("words_01") // 消费时 如果Topic不存在则会直接报错，只有在写Kafka时会自动创建Topic
                .setStartingOffsets(OffsetsInitializer.earliest()) // 当消费组无提交的消费偏移量时，指定消费的起始位置：earliest最早，latest最后
                .setGroupId("grp-01")
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        DataStreamSource<String> kafkaDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "wordsSource");

        SingleOutputStreamOperator<Tuple2<String, Integer>> kvDS = kafkaDS.flatMap((line, out) -> {
                    for (String word : line.split(",")) {
                        out.collect(Tuple2.of(word, 1));
                    }
                }, Types.TUPLE(Types.STRING, Types.INT)
        );

        /*
         * org.apache.flink.kafka.shaded.org.apache.kafka.common.KafkaException: Unexpected error in InitProducerIdResponse;
         *    The transaction timeout is larger than the maximum value allowed by the broker
         *    (as configured by transaction.max.timeout.ms).
         * kafka中的Broker所允许的最大的事务时间：15min （kafka的集群配置：transaction.max.timeout.ms）
         * Flink默认设置的事务的超时时间为：1h （Flink代码中的配置：transaction.timeout.ms）
         */

        Properties properties = new Properties();
        properties.setProperty("transaction.timeout.ms", 10 * 60 * 1000 + "");

        // 构建KafkaSink
        KafkaSink<String> kafkaSink = KafkaSink.<String>builder()
                .setTransactionalIdPrefix("trans_01")
                .setBootstrapServers("master:9092,node1:9092,node2:9092") //broker地址
                .setKafkaProducerConfig(properties)
                .setRecordSerializer(
                        KafkaRecordSerializationSchema
                                .<String>builder()
                                .setValueSerializationSchema(new SimpleStringSchema())
                                .setTopic("word_cnt_01") // 不存在会自动创建
                                .build()
                )
                // 使用EXACTLY_ONCE时，写入Kafka默认是以事务的方式写入
                .setDeliverGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                .build();

        kvDS.keyBy(kv -> kv.f0)
                .sum(1)
                .map(t2 -> t2.f0 + "," + t2.f1)
                .sinkTo(kafkaSink);

        env.execute();

    }
}
